package com.bdqn.t350.servlet;

import com.bdqn.t350.entity.Powerbattery;
import com.bdqn.t350.util.StringToUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet(name = "AddServlet_bak",urlPatterns = "/AddServlet_bak")
//标识该servlet支持文件上传功能
@MultipartConfig
public class AddServlet_bak extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("dopost....");
        req.setCharacterEncoding("UTF-8");
        //找到我们文件上传需要上传的目标目录
        String path = req.getSession().getServletContext().getRealPath("upload/");

        File fileSaveDir = new File(path);
        //判断path目录是否存在
        if(!fileSaveDir.exists()){
            //不存在该路径新建
            fileSaveDir.mkdirs();
        }
        //ufile表单的字段
        Part part = req.getPart("ufile");
        //得到真实上传文件的文件名称
        String fileName = extractFile(part);

        UUID uuid = UUID.randomUUID();
        String suff = StringToUtil.suff(fileName);
        String realFileName = uuid + suff;
        part.write(path + File.separator+realFileName);

        Powerbattery powerbattery = new Powerbattery();
        powerbattery.setRealFileName(realFileName);
        powerbattery.setSaveFileName(fileName);
    }

    private String extractFile(Part part){
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if(s.trim().startsWith("filename")){
                return s.substring(s.indexOf("=")+2,s.length()-1);
            }
        }
        return "";
    }


}
